package com.demo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo.common.kit.Ret;

@Controller
public class LoginController extends BaseController {

	@GetMapping(value = "login")
	public String login() {
		return "login";
	}

	@GetMapping("/dologin")
	@ResponseBody
	public Ret doLogin(String username, String password) {
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken usernamePasswordToken = null;
		String message = "";
		try {
			if (!currentUser.isAuthenticated()) {
				usernamePasswordToken = new UsernamePasswordToken(username, password);
				usernamePasswordToken.setRememberMe(true);
				currentUser.login(usernamePasswordToken);
			}
			return Ret.ok();
		} catch (UnknownAccountException e) {
			message = "账号不存在！";
		} catch (LockedAccountException e) {
			message = "账号已锁定！";
		} catch (AuthenticationException e) {
			message = "用户名或密码不正确！";
		}
		if (usernamePasswordToken != null) {
			usernamePasswordToken.clear();
		}
		return Ret.fail("message", message);
	}

	@GetMapping("/logout")
	public void logout() {
		getSubject().getSession().removeAttribute("user");//清除登录用户缓存
		getSubject().logout();
	}

	@RequestMapping("/403")
	public String unauth() {
		return "403";
	}
}
